package com.api.user.service.impl;

import com.api.base.dao.UserMapper;
import com.api.base.model.User;
import com.api.common.mybatis.ResultMap;
import com.api.core.config.AuthUser;
import com.api.user.dao.CompanionGameMapper;
import com.api.user.dao.MessageMapper;
import com.api.user.enums.IdentificationStatusEnums;
import com.api.user.model.*;
import com.api.user.service.*;
import com.api.core.service.AbstractService;
import com.api.user.vo.MessagePage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

import com.api.common.JSONUtils;
import com.api.core.response.Result;
import com.api.core.response.ResultGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * Created by wanghuiwen on 2021/03/29.
 */
@Service
@Transactional
public class MessageServiceImpl extends AbstractService<Message> implements MessageService {
    @Resource
    private MessageMapper messageMapper;

    @Resource
    private MessageRoleService messageRoleService;

    @Resource
    private MessageReadService messageReadService;

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private CompanionGameMapper companionGameMapper;

    @Resource
    private ManageInfoService manageInfoService;

    @Resource
    private IdentificationService identificationService;

    @Resource
    private UserMapper userMapper;


    @Override
    public Result list( Map<String, Object> params, String order, Integer page, Integer size){
//        Map<String, Object> params = JSONUtils.json2map(search);
        Map<String, Object> orderParams = JSONUtils.json2map(order);
        for (String key : orderParams.keySet()) {
                if (orderParams.get(key) != null && orderParams.get(key).equals("ascending")) orderParams.put(key, "asc");
                if (orderParams.get(key) != null && orderParams.get(key).equals("descending")) orderParams.put(key, "desc");
            }
        PageHelper.startPage(page, size);
        orderParams.put("message_id","desc");
        List<Map<String, Object>> res = messageMapper.list(params, orderParams);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(res);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @Override
    public Result userList(AuthUser user, Map<String, Object> params, Map<String, Object> orderParams, Integer page, Integer size) {
//        params.put("roleId",roleId);
        UserInfo userInfo = userInfoService.findById(user.getId());
        for (String key : orderParams.keySet()) {
            if (orderParams.get(key) != null && orderParams.get(key).equals("ascending")) orderParams.put(key, "asc");
            if (orderParams.get(key) != null && orderParams.get(key).equals("descending")) orderParams.put(key, "desc");
        }

        //获取权限是所有的消息
        List<Integer> roleIds = new ArrayList<>();
        roleIds.add(1);
        if(StringUtils.isNotEmpty(userInfo.getVipLevel())){
            //付费会员
            roleIds.add(2);
        }else{
            //普通会员
            roleIds.add(3);
        }
        //判断用户是否是陪玩用户，如果是就获取权限是陪玩的消息
        List<ResultMap<String, Object>> c = companionGameMapper.list(params, orderParams);
        if(!c.isEmpty()){
            roleIds.add(4);
        }
        //判断用户是否是主持，如果是，就获取主持的消息
        if(user.getType() == 3){
            roleIds.add(5);
        }

        //判断用户是否认证过，如果没有，就获取未认证的消息
        if(!IdentificationStatusEnums.USER_LEVEL_NA.equals(user.getLevel())){
            roleIds.add(6);
        }
        params.put("roleIds",roleIds);
        PageHelper.startPage(page,size);
        List<Map<String, Object>> res1 = messageMapper.userList(params, orderParams);

        MessagePage<Map<String, Object>> pageInfo = new MessagePage<>(res1);
        Integer countRead = messageMapper.noRead(params);
        pageInfo.setNoRead(countRead);

        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @Override
    public void add(MessageAdd messageAdd) {
        Message message = new Message();
        message.setCreateTime(new Date().getTime());
        message.setMessageTitle(messageAdd.getMessageTitle());
        message.setMessageType(messageAdd.getMessageType());
        message.setMessageContent(messageAdd.getMessageContent());
        this.save(message);
        String [] roleIds = messageAdd.getRoleId().split(",");
        for(int i=0;i<roleIds.length;i++){
            MessageRole messageRole = new MessageRole();
            messageRole.setMessageId(message.getMessageId());
            messageRole.setRoleId(Long.parseLong(roleIds[i]));
            messageRoleService.save(messageRole);
        }
    }

    @Override
    public void userUpdate(Long userId,Long messageId, Integer state) {
        MessageRead messageRead = messageReadService.getById(messageId,userId);
        if(messageRead == null){
            messageRead = new MessageRead();
            if(state ==1){
                messageRead.setState(1);
                messageRead.setReadTime(new Date().getTime());
                messageRead.setFavorites(false);
            }else if(state ==3){
                messageRead.setState(2);
                messageRead.setFavorites(true);
            }else if(state ==2){
                messageRead.setState(2);
                messageRead.setFavorites(false);
            }else if(state ==4){
                messageRead.setState(3);
            }else if(state ==5){
                messageRead.setFavorites(false);
            }
            else {
                messageRead.setState(state);
            }

            messageRead.setMessageId(messageId);
            messageRead.setUserId(userId);
            messageReadService.save(messageRead);
        }else{
            if(state ==1){
                messageRead.setState(1);
                messageRead.setReadTime(new Date().getTime());
            }else if(state ==3){
                messageRead.setFavorites(true);
            }else if(state ==2){
                messageRead.setState(2);
            }else if(state ==4){
                messageRead.setState(3);
            }else if(state ==5){
                messageRead.setFavorites(false);
            }else {
                messageRead.setState(state);
            }
            messageReadService.updateState(messageRead);
        }
    }

    @Override
    public void delete(Long messageId) {
        Message message = this.findById(messageId);

        List<MessageRole> messageRoles = messageRoleService.getByMessageId(messageId);
        for(MessageRole messageRole: messageRoles){
            messageRoleService.deleteById(messageRole);
        }
        List<MessageRead> messageReads = messageReadService.getByMessageId(messageId);
        for(MessageRead messageRead:messageReads){
            messageReadService.deleteById(messageRead);
        }
        this.deleteById(message);
    }

    @Override
    public int noRead(Long id) {
        UserInfo userInfo = userInfoService.findById(id);
        //获取权限是所有的消息
        List<Integer> roleIds = new ArrayList<>();
        roleIds.add(1);
        if(StringUtils.isNotEmpty(userInfo.getVipLevel())){
            //付费会员
            roleIds.add(2);
        }else{
            //普通会员
            roleIds.add(3);
        }


        Map<String, Object> params = new HashMap<>();
        params.put("userId",id);
        //判断用户是否是陪玩用户，如果是就获取权限是陪玩的消息
        List<ResultMap<String, Object>> c = companionGameMapper.list(params, new HashMap<>());
        if(!c.isEmpty()){
            roleIds.add(4);
        }

        User user =userMapper.selectByPrimaryKey(id);
        //判断用户是否是主持，如果是，就获取主持的消息
        if(user.getType() == 3){
            roleIds.add(5);
        }

        //判断用户是否认证过，如果没有，就获取未认证的消息
        if(!IdentificationStatusEnums.USER_LEVEL_NA.equals(userInfo.getVipLevel())){
            roleIds.add(6);
        }
        params.put("roleIds",roleIds);

        Integer countRead = messageMapper.noRead(params);

        return  countRead;
    }
}
